//
//  AMEditInfoViewController.m
//  WeiDu_1_0
//
//  Created by foguo-mac-1 on 01/07/16.
//  Copyright (c) 2016 WeiDu Energy Tech. All rights reserved.
//

#import "HOEditInfoViewController.h"
#import "Logger.h"
#import "HOUtils.h"
#import "HOConstants.h"
static NSString *phoneNumber = @"0571-28207515";
@implementation HOEditInfoViewController
@synthesize placeHolder;
@synthesize navItemTitle;
@synthesize limitedCount;
@synthesize indexPath;
@synthesize fieldName;
@synthesize oldValue;
@synthesize keypadType;
@synthesize inputBoxHeight;
@synthesize isOneLine;
@synthesize needHideLimitedLbl;
@synthesize questionId;
@synthesize delegate;

- (id)initWithModule:(HO_MODULE_TYPE)type
{
    self.inputBoxHeight = 143;
    return [super initWithModule:type];
}

- (void)sendNow:(HOEditView *)endView
{
}
//@Override
- (void)viewDidLoad
{
    [super viewDidLoad];
    inputBox = [[HOEditView alloc]
                initWithFrame:CGRectMake(0,
                                         20,
                                         self.view.frame.size.width,
                                         self.inputBoxHeight)];
    oneLineView = [[UIView alloc]
                       initWithFrame:CGRectMake(-1,
                                                20,
                                                self.view.frame.size.width + 2,
                                                self.inputBoxHeight)];
    [oneLineView setBackgroundColor:[UIColor whiteColor]];
    oneLineView.layer.borderWidth  = 1;
    oneLineView.layer.borderColor = UIColorFromRGB(0xcdcdcd).CGColor;
    oneLineInputBox = [[UITextField alloc]
                       initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
                                                0,
                                                self.view.frame.size.width - HO_HORIZONAL_PADDING * 2,
                                                self.inputBoxHeight)];
    
    oneLineInputBox.textColor = UIColorFromRGB(0x666000);
    oneLineInputBox.clearButtonMode = UITextFieldViewModeWhileEditing;
    oneLineInputBox.font = [UIFont systemFontOfSize:15];
    oneLineInputBox.delegate = self;
    inputBox.placeHolder = placeHolder;
//    oneLineInputBox.layer.borderWidth = 1;
    inputBox.limitedCount = limitedCount;
    if(needHideLimitedLbl)
        [inputBox hideLimitedCountView];
    [self.view addSubview:inputBox];
    [oneLineView addSubview:oneLineInputBox];
	[self.view addSubview:oneLineView];
	[inputBox getTextView].font = [UIFont systemFontOfSize:15];
	
	[self registerTapGesture];
    
}

- (void)hideKeyboard
{
	[inputBox resignFirstResponder];
}

- (void)displayPhoneNumberView
{
	
	self.isContactUS = YES;
	UIView *view = [[UIView alloc]
					initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
											 160 + HO_HORIZONAL_PADDING,
											 self.view.frame.size.width - 2 * HO_HORIZONAL_PADDING,
											 44)];
	[view setBackgroundColor:[UIColor whiteColor]];
	view.layer.borderWidth = [HOUtils defaultOnePixelConversion];
	view.layer.borderColor = UIColorFromRGB(0xcdcdcd).CGColor;
	view.layer.cornerRadius = 2;
	[view.layer setMasksToBounds:YES];
	UIButton *btn = [[UIButton alloc]
					initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
											 0,
											 self.view.frame.size.width - 2 * HO_HORIZONAL_PADDING,
											 44)];
	btn.titleLabel.font = [UIFont systemFontOfSize:16];
	btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
	[btn setTitle:[NSString stringWithFormat:@"%@%@", NSLocalizedString(@"反馈电话：", @"反馈电话："), phoneNumber] forState:UIControlStateNormal];
	[btn setTitleColor:MAIN_COLOR_NORMAL forState:UIControlStateNormal];
	[btn addTarget:self action:@selector(call:) forControlEvents:UIControlEventTouchUpInside];
	[view addSubview:btn];
	[self.view addSubview:view];
	[view release];
	
	
	
	UIButton *submitBtn = [[UIButton alloc]
						   initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
											160 + HO_HORIZONAL_PADDING * 3  + 44,
											  self.view.frame.size.width - 2 * HO_HORIZONAL_PADDING,
											  44)];
	[submitBtn setTitle:NSLocalizedString(@"确认提交", @"确认提交") forState:UIControlStateNormal];
	submitBtn.titleLabel.font = [UIFont systemFontOfSize:15];
	submitBtn.layer.cornerRadius = 5;
	[submitBtn.layer setMasksToBounds:YES];
	[submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
	[submitBtn setBackgroundImage:[HOUtils createImageWithColor:MAIN_COLOR_NORMAL forView:submitBtn] forState:UIControlStateNormal];
	[submitBtn addTarget:self action:@selector(submitContent) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:submitBtn];
	[submitBtn release];
}

- (void)call:(id)sender
{
	[HOUtils callPhoneNumber:phoneNumber];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if([self.fieldName isEqualToString:kHO_FIELD_TelPhone])
    {
        NSString *s = [textField.text stringByReplacingCharactersInRange:range withString:string];
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9-]+$" options:0 error:nil];
        NSTextCheckingResult *match = [regex firstMatchInString:s options:0 range:NSMakeRange(0, [s length])];
        return (match != nil);
    }
    else
    {
        return YES;
    }
    
}
- (void)hideLimitedLbl
{
    
    [inputBox hideLimitedCountView];
}

//@Override
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = YES;
    [self setNavigationItemTitle:navItemTitle];
    [super viewWillAppear:animated];
	[super registerKeyboard];
    [inputBox setText:oldValue];
    [inputBox setKeyboardType:keypadType];
    [inputBox setPlaceHolder:placeHolder];
    inputBox.frame = CGRectMake(0,
                                20,
                                self.view.frame.size.width,
                                self.inputBoxHeight);
    oneLineInputBox.placeholder = self.placeHolder;
    oneLineInputBox.keyboardType = self.keypadType;
    if(self.isOneLine)
    {
        [oneLineInputBox becomeFirstResponder];
        [oneLineInputBox setText:oldValue];
        inputBox.hidden = YES;
        inputBox.userInteractionEnabled = NO;
    }
    else
	{
		inputBox.hidden = NO;
        [[inputBox getTextView] becomeFirstResponder];
        oneLineView.userInteractionEnabled = NO;
        oneLineView.hidden = YES;
    }
	if(self.isContactUS)
	{
		inputBox.frame = CGRectMake(HO_HORIZONAL_PADDING,
									20,
									self.view.frame.size.width - 2 * HO_HORIZONAL_PADDING,
									self.inputBoxHeight);
		inputBox.layer.borderWidth = 1;
		[inputBox updateLayout];
	}
	
	[self displayRightButtonItemWithTitle:NSLocalizedString(@"确认", @"确认")];
	
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
	[super unregisterKeyboard];
}

- (void)hideHintView
{
    [super hideHintView];
}

- (void)submitContent
{
	NSString *content = @"";
    if(self.isOneLine)
    {
        content = [self getTrimingCharaFromTextField:oneLineInputBox];
    }
    else
    {
        content = [[inputBox getText] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    }
	if(content == nil || content.length == 0)
	{
		[self popupHintView:self.placeHolder];
		return;
	}
	if([self.fieldName isEqualToString:kHO_FIELD_TranslatorAddress])
	{
		if(self.delegate != nil && [self.delegate respondsToSelector:@selector(didFillInContent:withTag:)])
		{
			[self.delegate didFillInContent:content withTag:self.tag];
		}
		return;
	}
	if([self.fieldName isEqualToString:kHO_ACTION_SendFeedback])
	{
		[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_SendFeedback,
												kHO_FIELD_Content:content}];
	}
	else
	{
//		[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_ModifyUserItem,
//											self.fieldName:content}];
		if(self.delegate != nil && [self.delegate respondsToSelector:@selector(didFillInContent:withTag:)])
		{
			[self.delegate didFillInContent:content withTag:self.tag];
		}
	}

}

//@Override
- (void)rightButtonItemDidClick
{
//    [self submitContent];
	NSString *content = @"";
	if(self.isOneLine)
	{
		content = [self getTrimingCharaFromTextField:oneLineInputBox];
	}
	else
	{
		content = [[inputBox getText] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	}
	if(content == nil || content.length == 0)
	{
		[self popupHintView:self.placeHolder];
		return;
	}
	
	if(self.delegate != nil && [self.delegate respondsToSelector:@selector(didFillInContent:withTag:)])
	{
		[self.delegate didFillInContent:content withTag:self.tag];
	}
	
	[self goBack];
}

//@Override
- (void)didReceiveResponse:(HOBaseResponseEntity *)response
{
    if(![response.action isEqualToString:kHO_ACTION_ModifyUserItem]
	   && ![response.action isEqualToString:kHO_ACTION_SendFeedback])
        return;
	[super didReceiveResponse:response];
	if([response isRequestDone])
    {
		if([response.action isEqualToString:kHO_ACTION_ModifyUserItem])
        {
			
			int todoFillInfo = [[[response dataNode] objectForKey:kHO_FIELD_TodoFillInfo] intValue];
			[controller sendCommand:kHO_CMD_ModifyUserItem data:[NSNumber numberWithInt:todoFillInfo]];
			
            [self popupHintView:NSLocalizedString(@"修改成功!", @"修改成功!") inTime:1 needCallback:YES];
            self.view.userInteractionEnabled = NO;
		}
		if([response.action isEqualToString:kHO_ACTION_SendFeedback])
		{
			[self popupHintView:NSLocalizedString(@"提交成功!", @"提交成功!") inTime:1 needCallback:YES];
			self.view.userInteractionEnabled = NO;
		}
    }
	
}


#pragma mark
//@Override
- (void)hintDidHide
{
    self.view.userInteractionEnabled = YES;
    [self goBack];
}
//@Override
- (void)dealloc
{
	[HOUtils removeFromSuperViewForViews:oneLineInputBox, inputBox];
    [oneLineInputBox release];
    [inputBox release];
    
    [super dealloc];
}
@end
